async function loadCommunityEvents() {
    try {
        const response = await fetch('http://localhost:3000/api/community-events');
        if (!response.ok) {
            throw new Error('获取社区活动失败');
        }
        const events = await response.json();
        
        const container = document.getElementById('community-events-container');
        container.innerHTML = events.map(event => `
            <div class="event-card">
                <h3>${event.title}</h3>
                <div class="event-details">
                    <p><i class="fas fa-calendar"></i> ${new Date(event.event_date).toLocaleDateString()} ${event.event_time}</p>
                    <p><i class="fas fa-map-marker-alt"></i> ${event.location}</p>
                    <p><i class="fas fa-user-friends"></i> 剩余名额：${event.max_participants - event.current_participants}人</p>
                </div>
                <div class="event-description">
                    <p>${event.description}</p>
                </div>
                <div class="event-footer">
                    <div class="event-contact">
                        <p><i class="fas fa-user"></i> 联系人：${event.organizer}</p>
                        <p><i class="fas fa-phone"></i> 电话：${event.contact_phone}</p>
                        <button onclick="registerEvent(${event.id})" 
                            ${event.max_participants <= event.current_participants ? 'disabled' : ''} 
                            class="register-btn">
                            ${event.max_participants <= event.current_participants ? '名额已满' : '立即报名'}
                        </button>
                    </div>
                </div>
            </div>
        `).join('');
    } catch (error) {
        console.error('加载社区活动失败:', error);
        document.getElementById('community-events-container').innerHTML = 
            '<p class="error-message">加载社区活动失败，请稍后重试</p>';
    }
} 

// 查看健康报告
async function viewHealthReport() {
    if (!currentUserId) {
        alert('请先选择家庭成员');
        return;
    }
    
    try {
        const response = await fetch(`http://localhost:3000/api/health-report/${currentUserId}`);
        if (!response.ok) {
            throw new Error('获取健康报告失败');
        }
        const data = await response.json();
        
        showDataModal('health-report', data, 
            `${document.getElementById('familyMember').options[document.getElementById('familyMember').selectedIndex].text}的健康报告`);
    } catch (error) {
        console.error('错误:', error);
        alert('获取健康报告时发生错误');
    }
}

// 查看病史记录
async function viewMedicalHistory() {
    if (!currentUserId) {
        alert('请先选择家庭成员');
        return;
    }
    
    try {
        const response = await fetch(`http://localhost:3000/api/medical-history/${currentUserId}`);
        if (!response.ok) {
            throw new Error('获取病史记录失败');
        }
        const data = await response.json();
        
        showDataModal('medical-history', data,
            `${document.getElementById('familyMember').options[document.getElementById('familyMember').selectedIndex].text}的病史记录`);
    } catch (error) {
        console.error('错误:', error);
        alert('获取病史记录时发生错误');
    }
}

// 查看健康趋势
async function viewHealthTrends() {
    if (!currentUserId) {
        alert('请先选择家庭成员');
        return;
    }
    
    try {
        const response = await fetch(`http://localhost:3000/api/health-trends/${currentUserId}`);
        if (!response.ok) {
            throw new Error('获取健康趋势失败');
        }
        const data = await response.json();
        
        showDataModal('health-trends', data,
            `${document.getElementById('familyMember').options[document.getElementById('familyMember').selectedIndex].text}的健康趋势`);
    } catch (error) {
        console.error('错误:', error);
        alert('获取健康趋势时发生错误');
    }
}

// 显示数据模态框
function showDataModal(type, data, title) {
    currentDataType = type;
    currentData = data;
    
    const modal = document.getElementById('dataModal');
    const titleElement = document.getElementById('dataModalTitle');
    const displayArea = document.getElementById('dataDisplayArea');
    const editButton = document.getElementById('editButton');
    
    titleElement.textContent = title;
    
    let displayContent = '';
    switch(type) {
        case 'health-report':
            displayContent = `
                <div class="data-section">
                    <p><strong>血压：</strong>${data.bloodPressure}</p>
                    <p><strong>心率：</strong>${data.heartRate}</p>
                    <p><strong>血糖：</strong>${data.bloodSugar}</p>
                    <p><strong>体重：</strong>${data.weight}</p>
                    <p><strong>身高：</strong>${data.height}</p>
                    <p><strong>BMI：</strong>${data.bmi}</p>
                    <p><strong>体温：</strong>${data.temperature}</p>
                    <p><strong>检查日期：</strong>${new Date(data.lastUpdate).toLocaleDateString()}</p>
                </div>
            `;
            break;
        case 'medical-history':
            displayContent = data.map(record => `
                <div class="medical-record">
                    <p><strong>就诊日期：</strong>${new Date(record.visitDate).toLocaleDateString()}</p>
                    <p><strong>就诊医院：</strong>${record.hospital}</p>
                    <p><strong>科室：</strong>${record.department}</p>
                    <p><strong>医生：</strong>${record.doctor}</p>
                    <p><strong>诊断：</strong>${record.diagnosis}</p>
                    <p><strong>用药：</strong>${record.medication}</p>
                    <p><strong>医嘱：</strong>${record.doctorAdvice}</p>
                </div>
            `).join('');
            break;
        case 'health-trends':
            displayContent = `
                <div class="trend-section">
                    <h4>血压趋势</h4>
                    <p>最近记录：${data.bloodPressure.latest}</p>
                    <p>变化趋势：${data.bloodPressure.trend}</p>
                    
                    <h4>体重变化</h4>
                    <p>最近记录：${data.weight.latest}</p>
                    <p>变化趋势：${data.weight.trend}</p>
                    
                    <h4>血糖水平</h4>
                    <p>最近记录：${data.bloodSugar.latest}</p>
                    <p>变化趋势：${data.bloodSugar.trend}</p>
                </div>
            `;
            break;
        case 'advice':
            displayContent = data.content.split('\n').map(line => `<p>${line}</p>`).join('');
            break;
        case 'consultation':
            displayContent = `
                <div class="consultation-form">
                    <div class="form-group">
                        <label>选择科室：</label>
                        <select id="department" required>
                            <option value="">请择科室</option>
                            <option value="内科">内科</option>
                            <option value="外科">外科</option>
                            <option value="骨科">骨科</option>
                            <option value="心内科">心内科</option>
                            <option value="神经内科">神经内科</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>症状描述：</label>
                        <textarea id="symptoms" rows="4" placeholder="请详细描述您的症状..." required></textarea>
                    </div>
                    <div class="form-group">
                        <label>期望咨询时间：</label>
                        <input type="datetime-local" id="consultationTime" required>
                    </div>
                    <button onclick="submitConsultation()" class="submit-btn">提交咨询</button>
                </div>
            `;
            break;
            
        case 'appointment':
            displayContent = `
                <div class="appointment-form">
                    <div class="form-group">
                        <label>选择医院：</label>
                        <select id="hospital" required>
                            <option value="">请选择医院</option>
                            <option value="市第一人民医院">市第一人民医院</option>
                            <option value="市第二人民医院">市第二人民医院</option>
                            <option value="社区卫生服务中心">社区卫生服务中心</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>选择科室：</label>
                        <select id="appointmentDepartment" required>
                            <option value="">请选择科室</option>
                            <option value="内科">内科</option>
                            <option value="外科">外科</option>
                            <option value="骨科">骨科</option>
                            <option value="心内科">心内科</option>
                            <option value="神经内科">神经内科</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>预约日期：</label>
                        <input type="date" id="appointmentDate" required>
                    </div>
                    <div class="form-group">
                        <label>就诊说明：</label>
                        <textarea id="appointmentNote" rows="4" placeholder="请简要描述就医目的..." required></textarea>
                    </div>
                    <button onclick="submitAppointment()" class="submit-btn">提交预约</button>
                </div>
            `;
            break;
    }
    
    displayArea.innerHTML = displayContent;
    editButton.style.display = ['consultation', 'appointment'].includes(type) ? 'none' : type === 'advice' ? 'inline-block' : 'none';
    modal.style.display = 'block';
}

// 关闭数据模态框
function closeDataModal() {
    document.getElementById('dataModal').style.display = 'none';
    document.getElementById('dataEditArea').style.display = 'none';
    document.getElementById('dataDisplayArea').style.display = 'block';
}

// 添加全局变量
let currentUserId = '';

// 添加页面加载完成后的初始化函数
document.addEventListener('DOMContentLoaded', function() {
    loadUserList();
    updateSelectedUser();
    loadCommunityEvents();
});

// 添加加载用户列表函数
async function loadUserList() {
    try {
        console.log('开始获取用户列表...');
        const response = await fetch('http://localhost:3000/api/users', {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        });
        
        if (!response.ok) {
            throw new Error('获取用户列表失败');
        }
        const users = await response.json();
        
        const select = document.getElementById('familyMember');
        select.innerHTML = '<option value="">请选择...</option>';
        
        users.forEach(user => {
            const age = calculateAge(new Date(user.birth_date));
            const option = document.createElement('option');
            option.value = user.id;
            option.textContent = `${user.name} (${age}岁)`;
            select.appendChild(option);
        });
    } catch (error) {
        console.error('加载用户列表失败:', error);
        alert('加载用户列表失败');
    }
}

// 添加更新选择用户函数
function updateSelectedUser() {
    const select = document.getElementById('familyMember');
    currentUserId = select.value;
    
    // 更新编辑按钮状态
    const editBtn = document.getElementById('editUserBtn');
    editBtn.disabled = !currentUserId;
    
    // 更新其他按钮状态
    const buttons = document.querySelectorAll('.data-cards button');
    buttons.forEach(button => {
        button.disabled = !currentUserId;
    });

    // 加载健康建议
    loadHealthAdvice();
}

// 添加计算年龄的辅助函数
function calculateAge(birthDate) {
    const today = new Date();
    let age = today.getFullYear() - birthDate.getFullYear();
    const monthDiff = today.getMonth() - birthDate.getMonth();
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
} 

// 加载健康建议
async function loadHealthAdvice() {
    if (!currentUserId) {
        document.getElementById('diet-advice').innerHTML = '<p>请先选择家庭成员</p>';
        document.getElementById('exercise-advice').innerHTML = '<p>请先选择家庭成员</p>';
        document.getElementById('mental-advice').innerHTML = '<p>请先选择家庭成员</p>';
        return;
    }

    try {
        const response = await fetch(`http://localhost:3000/api/health-advice/${currentUserId}`);
        if (!response.ok) {
            throw new Error('获取健康建议失败');
        }
        const adviceList = await response.json();

        adviceList.forEach(advice => {
            const element = document.getElementById(`${advice.advice_type}-advice`);
            if (element) {
                element.innerHTML = `
                    <div class="advice-content">
                        ${advice.content.split('\n').map(line => `<p>${line}</p>`).join('')}
                    </div>
                `;
                // 添加点击事件，点击整个建议卡片就显示编辑模态框
                element.closest('.advice-card').onclick = () => {
                    showDataModal('advice', {
                        content: advice.content,
                        type: advice.advice_type
                    }, `编辑${getAdviceTypeText(advice.advice_type)}`);
                };
            }
        });
    } catch (error) {
        console.error('加载健康建议失败:', error);
        document.getElementById('diet-advice').innerHTML = '<p class="error-message">加载失败</p>';
        document.getElementById('exercise-advice').innerHTML = '<p class="error-message">加载失败</p>';
        document.getElementById('mental-advice').innerHTML = '<p class="error-message">加载失败</p>';
    }
}

// 获取建议类型的中文文本
function getAdviceTypeText(type) {
    switch(type) {
        case 'diet': return '饮食建议';
        case 'exercise': return '运动建议';
        case 'mental': return '心理健康建议';
        default: return '建议';
    }
} 

// 在线问诊功能
function startConsultation() {
    if (!currentUserId) {
        alert('请先选择家庭成员');
        return;
    }
    
    showDataModal('consultation', {}, '在线问诊');
}

// 预约挂号功能
function makeAppointment() {
    if (!currentUserId) {
        alert('请先选择家庭成');
        return;
    }
    
    showDataModal('appointment', {}, '预约挂号');
}

// 修改提交在线问诊函数
async function submitConsultation() {  // 移除 event 参数
    try {
        const department = document.getElementById('department').value;
        const symptoms = document.getElementById('symptoms').value;
        const consultationTime = document.getElementById('consultationTime').value;
        
        // 添加输入验证
        if (!department || !symptoms || !consultationTime) {
            alert('请填写所有必填项');
            return;
        }

        const response = await fetch('/api/consultation', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                userId: currentUserId,
                department,
                symptoms,
                consultationTime
            })
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const result = await response.json();
        alert('咨询预约成功！');
        closeDataModal();
        
    } catch (error) {
        console.error('提交出错:', error);
        alert('提交失败，请稍后重试');
    }
}

// 提交预约挂号
async function submitAppointment() {
    const hospital = document.getElementById('hospital').value;
    const department = document.getElementById('appointmentDepartment').value;
    const appointmentDate = document.getElementById('appointmentDate').value;
    const note = document.getElementById('appointmentNote').value;
    
    if (!hospital || !department || !appointmentDate || !note) {
        alert('请填写完整信息');
        return;
    }
    
    try {
        const response = await fetch('/api/appointment', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                userId: currentUserId,
                hospital,
                department,
                appointmentDate,
                note
            })
        });
        
        if (!response.ok) {
            throw new Error('提交失败');
        }
        
        alert('预约挂号成功，请在预约时间准时就医');
        closeDataModal();
    } catch (error) {
        console.error('预约挂号失败:', error);
        alert('提交失败，请稍后重试');
    }
}

// 添加编辑活动函数
async function editEvent(eventId) {
    try {
        const response = await fetch(`/api/community-events/${eventId}`);
        if (!response.ok) {
            throw new Error('获取活动信息失败');
        }
        const event = await response.json();
        
        // 填充表单
        document.getElementById('eventId').value = event.id;
        document.getElementById('eventTitle').value = event.title;
        document.getElementById('eventType').value = event.event_type;
        document.getElementById('eventDate').value = event.event_date.split('T')[0];
        document.getElementById('eventTime').value = event.event_time;
        document.getElementById('eventLocation').value = event.location;
        document.getElementById('maxParticipants').value = event.max_participants;
        document.getElementById('eventDescription').value = event.description;
        document.getElementById('organizer').value = event.organizer;
        document.getElementById('contactPhone').value = event.contact_phone;
        
        // 更新模态框标题
        document.getElementById('eventModalTitle').textContent = '编辑活动';
        
        // 显示模态框
        document.getElementById('eventFormModal').style.display = 'block';
    } catch (error) {
        console.error('加载活动信息失败:', error);
        alert('加载活动信息失败，请稍后重试');
    }
}

// 添加删除活动函数
async function deleteEvent(eventId) {
    if (!confirm('确定要删除这个活动吗？')) {
        return;
    }
    
    try {
        const response = await fetch(`/api/community-events/${eventId}`, {
            method: 'DELETE'
        });
        
        if (!response.ok) {
            throw new Error('删活动失败');
        }
        
        // 重新加载活动列表
        loadCommunityEvents();
        alert('活动已成功删除');
    } catch (error) {
        console.error('删除活动失败:', error);
        alert('删除活动失败，请稍后重试');
    }
}

// 添加活动报名函数
async function registerEvent(eventId) {
    if (!currentUserId) {
        alert('请先选择家庭成员');
        return;
    }
    
    try {
        const response = await fetch('/api/event-registration', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                eventId,
                userId: currentUserId
            })
        });
        
        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.error || '报名失败');
        }
        
        alert('报名成功！');
        // 重新加载活动列表以更新状态
        loadCommunityEvents();
    } catch (error) {
        console.error('活动报名失败:', error);
        alert(error.message || '报名失败，请稍后重试');
    }
}

// 添加显示添加活动表单函数
function showAddEventForm() {
    // 清空表单
    document.getElementById('eventForm').reset();
    document.getElementById('eventId').value = '';
    document.getElementById('eventModalTitle').textContent = '添加社区活动';
    document.getElementById('eventFormModal').style.display = 'block';
}

// 添加关闭活动表单函数
function closeEventForm() {
    document.getElementById('eventFormModal').style.display = 'none';
}

// 添加处理活动表单提交函数
async function handleEventSubmit(event) {
    event.preventDefault();
    
    const eventId = document.getElementById('eventId').value;
    const formData = {
        title: document.getElementById('eventTitle').value,
        event_type: document.getElementById('eventType').value,
        event_date: document.getElementById('eventDate').value,
        event_time: document.getElementById('eventTime').value,
        location: document.getElementById('eventLocation').value,
        max_participants: document.getElementById('maxParticipants').value,
        description: document.getElementById('eventDescription').value,
        organizer: document.getElementById('organizer').value,
        contact_phone: document.getElementById('contactPhone').value
    };
    
    try {
        const url = eventId 
            ? `/api/community-events/${eventId}`
            : '/api/community-events';
            
        const method = eventId ? 'PUT' : 'POST';
        
        const response = await fetch(url, {
            method,
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        });
        
        if (!response.ok) {
            throw new Error('保存活动���败');
        }
        
        closeEventForm();
        loadCommunityEvents();
        alert(eventId ? '活动更新成功' : '活动添加成功');
    } catch (error) {
        console.error('保存活动失败:', error);
        alert('保存失败，请稍后重试');
    }
}

// 添加切换编辑模式函数
function toggleEdit() {
    const displayArea = document.getElementById('dataDisplayArea');
    const editArea = document.getElementById('dataEditArea');
    const editButton = document.getElementById('editButton');
    const editFields = document.getElementById('editFields');
    
    if (editArea.style.display === 'none') {
        // 切换到编辑模式
        displayArea.style.display = 'none';
        editArea.style.display = 'block';
        editButton.style.display = 'none';
        
        // 根据当前数据类型生成编辑表单
        let formContent = '';
        switch(currentDataType) {
            case 'advice':
                formContent = `
                    <div class="form-group">
                        <label>修改建议内容：</label>
                        <textarea id="editContent" rows="10" class="form-control">${currentData.content}</textarea>
                    </div>
                `;
                break;
            // 可以添加其他类型的编辑表单
        }
        editFields.innerHTML = formContent;
    }
}

// 添加取消编辑函数
function cancelEdit() {
    const displayArea = document.getElementById('dataDisplayArea');
    const editArea = document.getElementById('dataEditArea');
    const editButton = document.getElementById('editButton');
    
    displayArea.style.display = 'block';
    editArea.style.display = 'none';
    editButton.style.display = 'inline-block';
}

// 添加处理数据提交函数
async function handleDataSubmit(event) {
    event.preventDefault();
    
    try {
        let updateData;
        switch(currentDataType) {
            case 'advice':
                updateData = {
                    content: document.getElementById('editContent').value,
                    type: currentData.type
                };
                
                const response = await fetch(`/api/advice/${currentUserId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(updateData)
                });
                
                if (!response.ok) {
                    throw new Error('更新失败');
                }
                
                // 更新显示
                document.getElementById('dataDisplayArea').innerHTML = 
                    updateData.content.split('\n').map(line => `<p>${line}</p>`).join('');
                
                // 更新健康建议显示
                loadHealthAdvice();
                break;
            // 可以添加其他类型的数据处理
        }
        
        // 切换回显示模式
        cancelEdit();
        alert('更新成功');
    } catch (error) {
        console.error('更新失败:', error);
        alert('更新失败，请稍后重试');
    }
}

// 添加全局变量来跟踪当前数据类型和数据
let currentDataType = '';
let currentData = null;